import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

import 'package:get/get.dart';
import 'package:getx_learn/app/common/widgets/widgets.dart';
import 'package:getx_learn/app/modules/weichat_post/api/index.dart';
import 'package:getx_learn/app/modules/weichat_post/entity/index.dart';
import 'package:getx_learn/app/modules/weichat_post/modules/post/constant/config.dart';
import 'package:getx_learn/app/modules/weichat_post/modules/post/controllers/post_controller.dart';
import 'package:getx_learn/app/modules/weichat_post/styles/index.dart';
import 'package:getx_learn/app/modules/weichat_post/util/bottom_sheet.dart';
import 'package:getx_learn/app/modules/weichat_post/util/du_picker.dart';
import 'package:getx_learn/app/modules/weichat_post/util/index.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/appbar.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/index.dart';
import 'package:getx_learn/app/routes/app_pages.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../controllers/timeline_controller.dart';

class TimelineView extends GetView<TimelineController> {
  TimelineView({Key? key}) : super(key: key);

  // 浮动层管理
  OverlayState? _overlayState;

  // 遮罩层
  OverlayEntry? _shadeOverEntry;

  // 更多按钮的位置 offset
  Offset _btnOffset = Offset.zero;

  // 获取更多按钮的位置 offset
  void _getBtnOffset(GlobalKey key) {
    final RenderBox? renderBox =
        key.currentContext?.findRenderObject() as RenderBox?;
    final Offset offset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
    _btnOffset = offset;
  }

  @override
  Widget build(BuildContext context) {
    // 初始化层管理对象
    _overlayState = Overlay.of(context);

    controller.build(context);

    return Obx(() => Scaffold(
          // 相当于 android:fitsSystemWindows
          // 如果为真，并且指定了[appBar]，则[body]的高度为 扩展到包括应用栏的高度和主体的顶部 与应用栏的顶部对齐。
          extendBodyBehindAppBar: true,
          appBar: AppBarWidget(
            automaticallyImplyLeading: false,
            backgroundColor: controller.appBarColor.value,
            actions: [
              GestureDetector(
                onTap: () {
                  _onPublish(context);
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: spacing),
                  child: Icon(
                    Icons.camera_alt,
                  ),
                ),
              ),
            ],
          ),
          body: _mainView(context),

          // bottomSheet 和 bottomNavigationBar 虽然都可以实现底部弹出
          // 但是 bottomSheet的还可以拖拽(拖拽可以关闭的)，而且 SafeArea 无效，
          // 所以 bottomNavigationBar 更合适些
          // bottomSheet: ,
          // 底部评论栏
          bottomNavigationBar: controller.isShowInput.value
              ? _buildCommentBar(context)
              : SizedBox.shrink(),
        ));
  }

  Widget _mainView(BuildContext context) {
    print("Get.context = ${Get.context}");
    // CustomScrollView 可以总体滚动，处理滚动冲突，
    return GestureDetector(
      onTap: () {
        if (controller.isShowInput.value) {
          _onSwitchCommentBar();
        }
      },
      child: CustomScrollView(
        controller: controller.scrollController,
        slivers: [
          // 头部
          // 需要是一些可以处理滚动冲突的组件
          SliverToBoxAdapter(
            child: _buildHeader(context),
          ),

          // padding
          SliverPadding(padding: EdgeInsets.only(bottom: spacing)),

          // 列表
          _buildList(context),
        ],
      ),
    );
  }

  // 头部
  Widget _buildHeader(BuildContext context) {
    // 获取屏幕宽度
    final width = MediaQuery.of(context).size.width;
    final user = controller.user;
    return user == null
        ? const Text('Loading...')
        : Stack(
            children: [
              // 背景
              Padding(
                padding: const EdgeInsets.only(
                  bottom: 10,
                ),
                child: SizedBox(
                  width: width,
                  child: Image.network(
                    user.cover ?? "",
                    height: width * 0.75,
                    fit: BoxFit.cover,
                  ),
                ),
              ),

              // 昵称、头像
              Positioned(
                right: spacing,
                bottom: 0,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 昵称
                    Text(
                      user.nickname ?? "",
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                        // 设置字间距
                        letterSpacing: 2,
                        // 行高
                        height: 1.8,
                        shadows: [
                          Shadow(
                            color: Colors.black,
                            offset: Offset(1, 1),
                            blurRadius: 2,
                          ),
                          Shadow(
                            color: Colors.amber,
                            offset: Offset(2, 2),
                            blurRadius: 2,
                          ),
                        ],
                      ),
                    ),
                    // 头像
                    Image.network(
                      user.avator ?? "",
                      width: 48,
                      height: 48,
                      fit: BoxFit.cover,
                    ),
                  ],
                ),
              ),
            ],
          );
  }

  // 列表
  Widget _buildList(BuildContext context) {
    // 处理嵌套滚动，滚动组件需要使用 SliverList 包裹

    return Obx(() {
      final list = controller.items;
      return SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            final item = list[index];
            return _buildListItem(item);
          },
          childCount: list.length,
        ),
      );
    });
  }

  // 列表项
  Widget _buildListItem(TimelineModel item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 正文、图片、视频
        _buildContent(item),

        // 点赞列表
        _buildLikeList(item),

        // 评论
        _buildCommentList(item),
      ],
    );
  }

  // 正文、图片、视频
  Padding _buildContent(TimelineModel item) {
    int imageCount = item.images?.length ?? 0;
    GlobalKey btnKey = GlobalKey();

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头像
          Image.network(
            item.user?.avator ?? "",
            width: 48,
            height: 48,
            fit: BoxFit.cover,
          ),

          SpaceHorizontalWidget(),

          // 右侧
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 昵称
                Text(
                  item.user?.nickname ?? "",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),

                SpaceVerticalWidget(),

                // 正文
                // Text(
                //   item.content ?? "",
                //   style: TextStyle(
                //     fontSize: 16,
                //     color: Colors.black54,
                //   ),
                // ),
                TextMaxLinesWdiget(content: item.content ?? ""),

                SpaceVerticalWidget(),

                // 视频
                if (item.postType == "2")
                  LayoutBuilder(builder:
                      (BuildContext context, BoxConstraints constraints) {
                    double ingWidth = constraints.maxWidth * 0.7;
                    return GestureDetector(
                      onTap: () {
                        _onGallery(item: item);
                      },
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          // 图
                          Image.network(
                            DuTools.imageUrlFormat(item.video?.cover ?? "",
                                width: 400),
                            height: ingWidth,
                            width: ingWidth,
                            fit: BoxFit.cover,
                          ),

                          // 播放图标
                          Positioned(
                            child: Icon(
                              Icons.play_circle_fill_outlined,
                              color: Colors.white,
                              size: 32,
                            ),
                          ),
                        ],
                      ),
                    );
                  }),

                // 九宫格图片列表
                // 少量图片的不用这个 GridView.builder，因为里面做了回收，对性能有损耗
                // if (item.images != null && item.images!.isNotEmpty)
                //   GridView.builder(
                //     shrinkWrap: true,
                //     physics: NeverScrollableScrollPhysics(),
                //     itemCount: item.images!.length,
                //     gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //       crossAxisCount: 3,
                //       crossAxisSpacing: 4,
                //       mainAxisSpacing: 4,
                //     ),
                //     itemBuilder: (context, index) {
                //       return Image.network(
                //         DuTools.imageUrlFormat(item.images![index],),
                //         fit: BoxFit.cover,
                //       );
                //     },
                //   ),

                // 少量图片可以使用 Wrap 这种自动换行的这种方式
                // 使用 LayoutBuilder 来动态计算图片的宽度
                if (item.postType == "1")
                  LayoutBuilder(
                    builder:
                        (BuildContext context, BoxConstraints constraints) {
                      double imgWidget = imageCount == 1
                          ? constraints.maxWidth * 0.7
                          : imageCount == 2
                              ? (constraints.maxWidth - spacing) / 2
                              : (constraints.maxWidth - spacing * 2) / 3;

                      return Wrap(
                        spacing: spacing,
                        runSpacing: spacing,
                        children: item.images!.map((e) {
                          return GestureDetector(
                            onTap: () {
                              _onGallery(src: e, item: item);
                            },
                            child: SizedBox(
                              width: imgWidget,
                              height: imgWidget,
                              child: Image.network(
                                DuTools.imageUrlFormat(e),
                                width: imgWidget,
                                height: imgWidget,
                                fit: BoxFit.cover,
                              ),
                            ),
                          );
                        }).toList(),
                      );
                    },
                  ),
                // Wrap(
                //   spacing: 4,
                //   runSpacing: 4,
                //   children: item.images!.map((e) {
                //     return Image.network(
                //       DuTools.imageUrlFormat(e),
                //       width: 100,
                //       height: 100,
                //       fit: BoxFit.cover,
                //     );
                //   }).toList(),
                // ),

                SpaceVerticalWidget(),

                // 位置
                Text(
                  item.location ?? "",
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.black54,
                  ),
                ),

                SpaceVerticalWidget(),

                // KeyboardVisibilityBuilder(
                //     builder: (context, isKeyboardVisible) {
                //   return Text(
                //     'The keyboard is: ${isKeyboardVisible ? 'VISIBLE' : 'NOT VISIBLE'}',
                //   );
                // }),

                // 时间，更多按钮
                Row(
                  children: [
                    Text(
                      item.publishDate ?? "",
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.black54,
                      ),
                    ),

                    SpaceVerticalWidget(),

                    Spacer(),

                    // 更多按钮
                    GestureDetector(
                      onTap: () {
                        // 获取按钮位置
                        _getBtnOffset(btnKey);

                        controller.currentItem.value = item;

                        // 显示遮罩层
                        _onShowMenu(onTap: _onCloseMenu);
                      },
                      child: Container(
                        key: btnKey,
                        decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.circular(2),
                        ),
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: const Icon(
                          Icons.more_horiz,
                          color: Colors.black54,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 发布
  _onPublish(BuildContext context) async {
    // 获取选取的结果
    final result =
        await DuBottomSheet(null).wxPicker<List<AssetEntity>>(context);

    if (result == null || result.isEmpty) {
      return;
    }

    final postType =
        (result.length == 1 && result.first.type == AssetType.video)
            ? PostType.video
            : PostType.image;

    // 跳转到朋友圈页面
    Map<String, dynamic> arguments = {
      "postType": postType,
      "selectedAssets": result,
    };
    Get.toNamed(Routes.POST, arguments: arguments);
  }

  // 显示菜单
  _onShowMenu({Function()? onTap}) {
    _shadeOverEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          child: GestureDetector(
            onTap: onTap,
            child: Stack(
              children: [
                // 遮罩层
                AnimatedContainer(
                  duration: const Duration(microseconds: 300),
                  // width: 200,
                  // height: 100,
                  color: Colors.black.withOpacity(0.4),
                ),

                // 菜单
                AnimatedBuilder(
                    animation: controller.animationController,
                    builder: (context, child) {
                      return Positioned(
                        top: _btnOffset.dy - 10,
                        left: _btnOffset.dx - 5 - controller.sizeTween.value,
                        child: SizedBox(
                          width: controller.sizeTween.value,
                          height: 40,
                          child: _buildIsLikeMenu(
                              controller.currentItem.value ?? TimelineModel()),
                        ),
                      );
                    }),
              ],
            ),
          ),
        );
      },
    );

    // 添加悬浮层到悬浮管理器
    _overlayState!.insert(_shadeOverEntry!);

    // 延时启动菜单
    Future.delayed(Duration(milliseconds: 100), () {
      if (controller.animationController.status == AnimationStatus.dismissed) {
        controller.animationController.forward();
      }
    });
  }

  // 关闭菜单
  _onCloseMenu() async {
    if (controller.animationController.status == AnimationStatus.completed) {
      // 让动画恢复初始化位置
      await controller.animationController.reverse();
      _shadeOverEntry?.remove();
      _shadeOverEntry = null;
    }
  }

  // 是否喜欢菜单
  _buildIsLikeMenu(TimelineModel item) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.black87, borderRadius: BorderRadius.circular(4)),
      child: LayoutBuilder(builder: (context, BoxConstraints constraints) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 喜欢
            if (constraints.maxWidth > 80)
              TextButton.icon(
                onPressed: () {
                  _onLike();
                },
                icon: Icon(
                  Icons.favorite,
                  color: item.isLike == true ? Colors.redAccent : Colors.white,
                  size: 16,
                ),
                label: Text(
                  item.isLike == true ? "取消" : "喜欢",
                  style: textStylePopMenu,
                ),
              ),

            // 评论
            if (constraints.maxWidth > 160)
              TextButton.icon(
                onPressed: () {
                  // 显示评论栏
                  _onSwitchCommentBar();
                  // 关闭菜单
                  _onCloseMenu();
                },
                icon: Icon(
                  Icons.chat_bubble_outline,
                  color: Colors.white,
                  size: 16,
                ),
                label: Text(
                  "评论",
                  style: textStylePopMenu,
                ),
              ),
          ],
        );
      }),
    );
  }

  // 点赞操作
  void _onLike() {
    if (controller.onLine() == true) {
      // 关闭菜单
      _onCloseMenu();
    }
  }

  // 跳转相册
  void _onGallery({String? src, TimelineModel? item}) {
    Navigator.push(Get.context!, MaterialPageRoute(builder: (context) {
      return GalleryWidget(
        initialIndex: src == null ? 1 : item?.images?.indexOf(src) ?? 1,
        timelineModel: item,
        imageUrls: item?.images ?? [],
      );
    }));
  }

  // 点赞列表
  Widget _buildLikeList(TimelineModel item) {
    return Container(
      padding: EdgeInsets.all(spacing),
      color: Colors.grey[100],
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          Padding(
            padding: EdgeInsets.only(
              top: spacing,
            ),
            child: Icon(
              Icons.favorite_border_outlined,
              size: 20,
              color: Colors.black54,
            ),
          ),

          SpaceHorizontalWidget(),

          // 列表
          Expanded(
              child: Wrap(
            spacing: 5,
            runSpacing: 5,
            children: [
              for (LikeModel item in item.likes ?? [])
                Image.network(
                  item.avator ?? "",
                  height: 32,
                  width: 32,
                  fit: BoxFit.cover,
                ),
            ],
          )),
        ],
      ),
    );
  }

  /// 评论列表
  Widget _buildCommentList(TimelineModel item) {
    return Container(
      padding: EdgeInsets.all(spacing),
      color: Colors.grey[100],
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          Padding(
            padding: EdgeInsets.only(top: spacing),
            child: Icon(
              Icons.chat_bubble_outline,
              size: 20,
              color: Colors.black54,
            ),
          ),

          SpaceHorizontalWidget(),

          // 右侧评论列表
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                for (CommentModel comment in item.comments ?? [])
                  // 评论项目
                  Row(
                    children: [
                      // 头像
                      Image.network(
                        comment.user?.avator ?? "",
                        height: 32,
                        width: 32,
                        fit: BoxFit.cover,
                      ),

                      SpaceHorizontalWidget(),

                      // 昵称、时间、内容
                      Expanded(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 行 1 昵称、时间
                            Row(
                              children: [
                                // 昵称
                                Text(
                                  comment.user?.nickname ?? "",
                                  style: textStyleComment,
                                ),
                                Spacer(),
                                // 时间
                                Text(
                                  DuTools.dateTimeFormat(
                                    comment.publishDate ?? "",
                                  ),
                                ),
                              ],
                            ),

                            // 行 2 内容
                            Text(
                              comment.content ?? "",
                              style: textStyleComment,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 切换评论输入栏
  void _onSwitchCommentBar() {
    final isShowInput = !controller.isShowInput.value;
    controller.isShowInput.value = isShowInput;

    if (isShowInput) {
      // 请求焦点
      controller.focusNode.requestFocus();
    } else {
      // 去除焦点
      controller.focusNode.unfocus();
    }

    controller.textCommentEditingController.text = "";
  }

  // 评论
  void _onComment() {
    // 安全检查
    final _currentItem = controller.currentItem.value;
    if (_currentItem == null) return;

    // 设置状态
    _currentItem.comments?.add(CommentModel(
      content: controller.textCommentEditingController.text,
      user: controller.user,
      publishDate: DateTime.now().toString(),
    ));

    // 关闭
    _onSwitchCommentBar();

    // 执行请求
    TimelineApi.comment(
      _currentItem.id!,
      controller.textCommentEditingController.text,
    );
  }

  // 底部弹出评论栏
  Widget _buildCommentBar(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 100),
      padding: MediaQuery.of(context).viewInsets,
      // SafeArea 可以保证键盘弹出的时候，不会给某些不规则的视图遮挡
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.grey[100],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 评论输入框
              Row(
                children: [
                  // 输入框
                  Expanded(
                    child: TextField(
                      controller: controller.textCommentEditingController,
                      focusNode: controller.focusNode,
                      // 如果 keyboardType 是 TextInputType.none 则可以阻止键盘弹出
                      keyboardType: controller.isShowSystemKeyboard.value ? TextInputType.text : TextInputType.none,
                      textInputAction: TextInputAction.done,
                      decoration: InputDecoration(
                        hintText: "评论",
                        // 圆角边框
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                          borderSide: BorderSide.none,
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 0,
                        ),

                        filled: true,
                        fillColor: Colors.white,
                        hintStyle: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.black26,
                          letterSpacing: 2,
                        ),
                      ),
                      maxLines: 1,
                      minLines: 1,
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black87,
                      ),
                    ),
                  ),

                  SpaceHorizontalWidget(),

                  // 表情图标
                  GestureDetector(
                    onTap: () {
                      controller.isShowEmoji.value =
                          !controller.isShowEmoji.value;
                      if (controller.isShowEmoji.value == false) {
                        // 请求焦点
                         controller.focusNode.unfocus();
                        controller.isShowSystemKeyboard.value = true;
                        Future.delayed(Duration(milliseconds: 20), () {
                          controller.focusNode.requestFocus();
                        });
                      } else {
                        // 去除焦点
                         controller.isShowSystemKeyboard.value = false;
                        controller.focusNode.unfocus();
                        Future.delayed(Duration(milliseconds: 20), () {
                          controller.focusNode.requestFocus();
                        });
                      }
                    },
                    child: Icon(
                      controller.isShowEmoji.value
                          ? Icons.keyboard_alt_outlined
                          : Icons.mood_outlined,
                      size: 32,
                      color: Colors.black54,
                    ),
                  ),

                  SpaceHorizontalWidget(),

                  ElevatedButton(
                    onPressed:
                        !controller.isInputWords.value ? null : _onComment,
                    child: Text(
                      "发送",
                      style: TextStyle(fontSize: 16),
                    ),
                  ),
                ],
              ),

              // 微信表情列表
              if (controller.isShowEmoji.value)
                Container(
                  padding: EdgeInsets.all(spacing),
                  height: controller.keyboardHeight,
                  child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      // 横轴上的组件熟练
                      crossAxisCount: 7,
                      // 沿主轴的组件直接的逻辑像素数
                      mainAxisSpacing: 10,
                      // 沿横轴的组件直接的逻辑像素数
                      crossAxisSpacing: 10,
                    ),
                    itemCount: 100,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        color: Colors.grey[200],
                      );
                    },
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
